﻿#ifndef SERVERLISTMODEL_H
#define SERVERLISTMODEL_H

#include <QAbstractListModel>
#include <thread>
#include <list>
#include <atomic>

#include "QtChCharset.h"

class ServerListModel : public QAbstractListModel
{
    Q_OBJECT
public:
    static ServerListModel * Singleton();
public:
    enum BluetoothDeviceRole {
        ServerNameRole = Qt::DisplayRole,
        ServerAddrRole = Qt::UserRole,
        FtpIPRole,
        FtpPortRole,
        FtpNameRole,
    };
    Q_ENUM(BluetoothDeviceRole)

    ServerListModel(QObject *parent = nullptr);
    ~ServerListModel();

    virtual int rowCount(const QModelIndex & = QModelIndex()) const override;
    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    virtual QHash<int, QByteArray> roleNames() const override;

public slots:
    //Q_INVOKABLE QVariantMap get(int row) const;
    // 增加
    Q_INVOKABLE void addServer(const QString& serverName, const QString& serverAddr, const QString& ftpIP, int ftpPort, const QString& ftpName);
    // 删除行
    Q_INVOKABLE void remove(int row);
    // 清空
    Q_INVOKABLE void clear();
public slots:
    // 扫描局域网内的FTP服务
    void scanServer(int ftpPort);
    // 打开FTP
    void openServer(QString ftpIP, int ftpPort, QString userName, QString userPassword);
    // FTP地址复制到剪切板
    void ftpAddrToClipboard(QString ftpIP, int ftpPort, QString userName, QString userPassword);
Q_SIGNALS:
    // 发送显示消息
    void signalShowMsg(QString msg);
private:
    // 列表每行信息
    class ServerInfo
    {
    public:
        QString serverName;
        QString serverAddr;
        QString ftpIP;
        int ftpPort = 0;
        QString ftpName;
    public:
        ServerInfo()
        {}
        ServerInfo(const QString& serverName, const QString& serverAddr, const QString& ftpIP, int ftpPort, const QString& ftpName)
        {
            this->serverName = serverName;
            this->serverAddr = serverAddr;
            this->ftpIP = ftpIP;
            this->ftpPort = ftpPort;
            this->ftpName = ftpName;
        }
    };

    QList<ServerInfo> mServerInfoList;
private:
    // 检查是否为FTP
    void pingFtp(QString strIp, int iPort);
    // 当前检查FTP任务数
    //std::atomic<int> pingFtpThreadCount = 0;
    volatile int pingFtpThreadCount = 0;
protected:
    // 重载自定义事件
    virtual void customEvent(QEvent *event) override;
private:
    // 获取同局域网IP地址
    void GetLANIPs(std::vector<std::string>& ipVec);
    // 获取本地IP和掩码
    void GetLocalAddrQt(std::vector<std::pair<std::string,std::string>>& addrVec);
    //void GetLocalAddrWindows(std::vector<std::string>& addrVec);
};

#endif // SERVERLISTMODEL_H
